package com.pengheng.state;

import com.pengheng.bean.WaterSensor;
import com.pengheng.transformation.aggregation.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class KeyedReducingStateDemo {


    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> sensorDS = env.socketTextStream("192.168.10.100", 7777).map(new WaterSensorMapFunction()).assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner((element, ts) -> element.getTs() * 1000L));

        sensorDS.keyBy(r -> r.getId()).process(new KeyedProcessFunction<String, WaterSensor, Integer>() {

            private ReducingState<Integer> sumVcState;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                ReducingStateDescriptor<Integer> reducingStateDescriptor = new ReducingStateDescriptor<>("reducingState", Integer::sum, Integer.class);
                sumVcState = getRuntimeContext().getReducingState(reducingStateDescriptor);
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<Integer> out) throws Exception {
                sumVcState.add(value.getVc());
                out.collect(sumVcState.get());
            }
        }).print();

        env.execute();
    }
}
